package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.CalculationBean;
import one.bugu.android.demon.bean.CapitalDetailBean;
import one.bugu.android.demon.bean.MedalBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.constant.MedalContant;
import one.bugu.android.demon.ui.activity.shop.MagicCalShopActivity;
import one.bugu.android.demon.ui.adapter.CalculationInfoAdapter;
import one.bugu.android.demon.ui.dialog.DialogContent;
import one.bugu.android.demon.ui.dialog.DialogMedal;
import one.bugu.android.demon.ui.refresh.SmartRefreshLayout;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshLoadmoreListener;
import one.bugu.android.demon.ui.refresh.listener.RefreshLayout;
import one.bugu.android.demon.ui.refresh.util.DensityUtil;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.ui.widget.MedalProgressView;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.OnViewClickListener;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.ShareImageUtils;
import one.bugu.android.demon.util.StatusBarUtils;

@LKContentView(R.layout.activity_calculationinfo)
public class CalculationActivity extends MyBaseActivity {
    /**
     * topBar
     */
    @LKInjectView(R.id.btbv_cal)
    private BaseTopBarView btbv_cal;

    /**
     * 算力明细列表
     */
    @LKInjectView(R.id.calculation_listview)
    private ListView listView;

    /**
     * 列表标题
     */
    @LKInjectView(R.id.tv_cal_title)
    private TextView tv_cal_title;

    /**
     * 刷新控件
     */
    @LKInjectView(R.id.ref_layout)
    private SmartRefreshLayout ref_layout;
    /**
     * 当前头衔
     */
    @LKInjectView(R.id.tv_cal_level)
    private TextView tv_cal_level;

    /**
     * 算力数量
     */
    private TextView calculationNum;

    /**
     * 算力商城按钮
     */
    private TextView tv_cal_shop;
    /**
     * 当前BGT数量
     */
    private TextView tv_cur_cal_num;

    /**
     * 下一级解锁数量
     */
    private TextView tv_cal_num_hint;

    /**
     * 头衔进度显示
     */
    private MedalProgressView pb_cal_progressBar;
    /**
     * 滑动组件
     */
    private HorizontalScrollView sc_progress_view;

    private int getPosition = -1;
    /**
     * 数据适配器
     */
    private CalculationInfoAdapter calculationInfoAdapter;

    String token;

    private int limit = 50;

    private int offset = 1;
    private String calCount;

    private boolean isShare = false;

    /**
     * 算力头衔数据
     */
    private List<MedalBean> powerTitle;

    @Override
    protected void initView() {
        super.initView();
        //设置状态栏状态
        StatusBarUtils.getInstance().setStatusBar("#5856D0", this, btbv_cal, true);
        //添加头布局
        //算力总数,头衔等级
        View powerTitleView = View.inflate(this, R.layout.layout_power_title, null);
        calculationNum = powerTitleView.findViewById(R.id.num_calculation);
        tv_cal_shop = powerTitleView.findViewById(R.id.tv_cal_shop);
        tv_cur_cal_num = powerTitleView.findViewById(R.id.tv_cur_cal_num);
        sc_progress_view = powerTitleView.findViewById(R.id.sc_progress_view);
        pb_cal_progressBar = powerTitleView.findViewById(R.id.pb_cal_progressBar);
        tv_cal_num_hint = powerTitleView.findViewById(R.id.tv_cal_num_hint);
        tv_cal_level = powerTitleView.findViewById(R.id.tv_cal_level);
        listView.addHeaderView(powerTitleView);
        //明细title
        View titleView = View.inflate(this, R.layout.layout_cal_details_title, null);
        listView.addHeaderView(titleView);


        //获取算力数据
        Intent intent = getIntent();
        calCount = intent.getStringExtra(Constant.CALCULATION);
        calculationNum.setText(calCount);

        token = PreferencesUtil.getInstance().getString(CalculationActivity.this, Constant.TOKEN);
        //设置适配器
        calculationInfoAdapter = new CalculationInfoAdapter(this);
        listView.setAdapter(calculationInfoAdapter);

        //设置默认头衔进度
        pb_cal_progressBar.setLayoutViewData(MedalContant.defCalMedalData, 0, 33);

        ref_layout.setEnableRefresh(true);//启用刷新
        ref_layout.setEnableLoadmore(true);//启用加载

    }

    /**
     * 获取算力信息的方法
     */
    @Override
    protected void initData() {
        super.initData();
        offset = 1;
        getData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //算力刷新逻辑
        int anInt = PreferencesUtil.getInstance().getInt(CalculationActivity.this, Constant.BUY_CAL, 0);
        if (anInt > 0) {
            PreferencesUtil.getInstance().putInt(CalculationActivity.this, Constant.BUY_CAL, 0);
            try {
                String trim = calculationNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                calCount = String.valueOf(num + anInt);
                calculationNum.setText(String.valueOf(num + anInt));
            } catch (Exception e) {
                e.printStackTrace();
            }
            offset = 1;
            getData();

            //农场首页刷新数据
            Intent intent = new Intent();
            intent.putExtra("CAL_NUM", calculationNum.getText().toString().trim());
            setResult(RESULT_OK, intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //分享返回
        if (isShare && powerTitle != null) {
            getCalMedal(String.valueOf(powerTitle.get(getPosition).getRowId()));
        }
        isShare = false;
    }

    /**
     * 获取数据
     */
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("wallteTypeId", "40");
        map.put("sort", "createTime");
        map.put("order", "desc");
        map.put("limit", String.valueOf(limit));
        map.put("offset", String.valueOf(offset));
        LKUtil.getHttpManager().postBody(HttpConstant.GETUSERWALLET_URL, map, handler);
    }


    /**
     * 获取算力信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<CapitalDetailBean> handler = new BaseHttpAsycResponceHandler<CapitalDetailBean>(false) {
        @Override
        public void onSuccess(CapitalDetailBean data) {
            super.onSuccess(data);
            if (offset == 1) {
                //头衔
                powerTitle = data.getPowerTitle();
                double count = Double.parseDouble(calCount);
                String haveGotTitle = data.getHaveGotTitle();
                for (int i = 0; i < powerTitle.size(); i++) {
                    MedalBean medalBean = powerTitle.get(i);
                    medalBean.setImageWidth(33);
                    medalBean.setImageHeight(33);
                    //头衔ID
                    String rowId = String.valueOf(powerTitle.get(i).getRowId());
                    //设置图标
                    if (count >= powerTitle.get(i).getMinNum()) {
                        if (!TextUtils.isEmpty(haveGotTitle) && haveGotTitle.contains(rowId)) {
                            //已经领取过
                            medalBean.setDrawableRes(MedalContant.hasGetMedalArr[i]);
                            medalBean.setCanClick(false);
                        } else {
                            //未领取
                            medalBean.setDrawableRes(MedalContant.calMedalArr[i]);
                            medalBean.setCanClick(true);
                        }
                    } else {
                        //没有达到的标准显示默认
                        if (!TextUtils.isEmpty(haveGotTitle) && haveGotTitle.contains(rowId)) {
                            //如果未达标的头衔之前领取过,此时显示降级图标
                            medalBean.setDrawableRes(MedalContant.downMedalImage);
                            medalBean.setCanClick(false);
                        } else {
                            //显示默认图标
                            medalBean.setDrawableRes(MedalContant.defMedalImage);
                            medalBean.setCanClick(false);
                        }
                    }
                }
                //设置算力等级显示
                setCalMedal(powerTitle);
            }
            //算力明细
            List<CalculationBean> calculationBeans = data.getFolwList();
            ref_layout.finishLoadmore();
            ref_layout.finishRefresh();
            if (offset == 1) {
                calculationInfoAdapter.updateData(calculationBeans);
            } else {
                calculationInfoAdapter.addData(calculationBeans);
            }
            ref_layout.setEnableLoadmore((calculationBeans.size() >= limit));
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ref_layout.finishLoadmore();
            ref_layout.finishRefresh();
        }

        @Override
        public void onError() {
            super.onError();
            ref_layout.finishLoadmore();
            ref_layout.finishRefresh();
        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();
        btbv_cal.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                showDesDialog();
            }
        });

        //刷新加载
        ref_layout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //加载数据
                offset++;
                getData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //刷新数据
                offset = 1;
                getData();
            }
        });

        //算力商城
        tv_cal_shop.setOnClickListener(new OnViewClickListener() {
            @Override
            protected void singleClick(View view) {
                IntentUtils.startAty(CalculationActivity.this, MagicCalShopActivity.class);
            }
        });

        //listview滑动监听
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                tv_cal_title.setVisibility(firstVisibleItem == 0 ? View.GONE : View.VISIBLE);
            }
        });

    }

    /**
     * 算力说明弹窗
     */
    private void showDesDialog() {
        DialogContent dialog = new DialogContent(this, R.style.DialogBottom, 0.55);
        View view = View.inflate(this, R.layout.dialog_calculation_content, null);
        TextView tv_calculation = view.findViewById(R.id.tv_calculation);
        String content = this.getResources().getString(R.string.str_calculation_des);
        MyTextUtils.getInstance().setParagraphSpacing(this, tv_calculation, content, 30, 8);
        dialog.setViewAndBackground(view, R.drawable.shape_dialog_content_bg);
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    /**
     * 算力头衔设置
     */
    private void setCalMedal(final List<MedalBean> powerTitle) {
        //设置进度
        pb_cal_progressBar.setLayoutViewData(powerTitle, Double.parseDouble(calCount), 33);
        pb_cal_progressBar.setOnViewClickEvent(new MedalProgressView.OnViewClickEvent() {
            @Override
            public void onViewLick(int position) {
                //点击事件处理
                getPosition = position;
                //显示弹窗
                showBgtMedalDialog(MedalContant.farmMedalImage[position], powerTitle.get(position).getTitleName(), position);
            }
        });
        //当前算力数量
        SpannableString bgtStr = MyTextUtils.getInstance().setAutoTextColor("当前算力  " + calCount, "[0-9]{1,}", "#5856D0");
        tv_cur_cal_num.setText(bgtStr);
        //下一等级解锁
        double dBgtNum = Double.parseDouble(calCount);
        int nextLevP = 0;
        for (int i = 0; i < powerTitle.size(); i++) {
            double maxNum = powerTitle.get(i).getMaxNum();
            double minNum = powerTitle.get(i).getMinNum();
            if (dBgtNum >= minNum && dBgtNum < maxNum) {
                nextLevP = i;
                //如果最高等级不再当前页面展示, 则滑动一段距离展示最高等级
                if (i > 4) {
                    //滑动一段距离保证最高等级显示
                    final int finalI = i;
                    sc_progress_view.post(new Runnable() {
                        @Override
                        public void run() {
                            sc_progress_view.scrollTo((finalI - 2) * DensityUtil.dp2px(MedalContant.MEDAL_HORIZONTAL_SPACE), 0);
                        }
                    });
                }
                break;
            }
        }
        int cueP = nextLevP + 1 >= MedalContant.calMedalArr.length - 1 ? MedalContant.calMedalArr.length - 1 : nextLevP + 1;
        String nextLevel = "算力达到" + (int) (powerTitle.get(cueP).getMinNum()) + "可解锁";
        SpannableString levelStr = MyTextUtils.getInstance().setAutoTextColor(nextLevel, "[0-9]{1,}", "#5856D0");
        tv_cal_num_hint.setText(levelStr);
        //当前头衔
        Drawable drawable = getResources().getDrawable(MedalContant.calMedalArr[cueP]);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_cal_level.setCompoundDrawables(drawable, null, null, null);
        tv_cal_level.setText(powerTitle.get(cueP).getTitleName());

    }

    /**
     * 显示算力头衔弹框
     */
    private void showBgtMedalDialog(int levImage, String levTitle, final int level) {
        final DialogMedal dialogMedal = new DialogMedal(this, R.style.DialogBottom);
        dialogMedal.setDialogBg(R.mipmap.icon_suanli_dialog_bg);
        dialogMedal.setImageRes(levImage);
        dialogMedal.setLevelTitle("");
        dialogMedal.setStatus(false);
        dialogMedal.setOnGetBtnClick(new DialogMedal.OnGetBtnClick() {
            @Override
            public void onGetBtnClickListener() {
                isShare = true;
                ShareImageUtils.getInstance().compShareImage(CalculationActivity.this, dialogMedal);
            }
        });
        dialogMedal.show();
    }

    /**
     * 算力头衔领取
     */
    private void getCalMedal(String titleId) {
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("titleId", titleId);
        LKUtil.getHttpManager().post(HttpConstant.GET_CAL_MEDAL, map, getHandler);
    }

    /**
     * 获取算力信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> getHandler = new BaseHttpAsycResponceHandler<String>(false) {
        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            ToastUtils.custom("领取成功");
            pb_cal_progressBar.getGive(getPosition);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);

        }

        @Override
        public void onError() {
            super.onError();

        }
    };

}
